// pages/event/event_report.js
//获取应用实例
const app = getApp()
const log = new app.appLogs()
const http = new app.appHttp()
import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast";
import Dialog from "../../miniprogram_npm/@vant/weapp/dialog/dialog";

Page({

    /**
     * 页面的初始数据
     */
    data: {
        address: null,//地址
        isluyin1: true,
        phone: "",
        latitude: null,
        longitude: null,
        textareaValue: null,//描述信息
        locationPermission: true,
        yuYinPath: '/common/image/yuyin.png',
        lyFile: null,
        fileList: [],
        audio: null,
        isYuYinPlay: false,
        isLuYinIndex: 1,
        isLuYin: false,
        recorderManager: null,
        radio: '',
        tpeylist: [],
        show: false,
        animationStatus: false,
        type: null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (app.globalData.userInfo != null) {

        } else {
            wx.navigateTo({
                url: '/pages/mine/login/login',
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 调用微信定位功能 根据坐标查询详细地址。
        //初始化音频播放器
        this.getEventType()
        this.getPhoneNum()
        this.data.audio = wx.createInnerAudioContext()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    changeAddress: function (e) {
        this.setData({
            address: e.detail.value,
        });
    },
    /**
     * 根据微信定位坐标，通过服务器查询上报地 祥址
     */
    getCurrentLocationByServer: function () {
        wx.showLoading({
            title: '定位中...',
        })
        const than = this;
        wx.getLocation({
            type: 'gcj02',
            altitude: true,
            isHighAccuracy: true,
            success: function (res) {
                wx.hideLoading();
                than.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,
                    locationPermission: false
                });
                http.get("open/address", {
                    latitude: res.latitude,
                    longitude: res.longitude
                }).then((res) => {
                    than.setData({
                        address: res.data.data,
                    })
                })
            },
        })
    },
    /**
     * 重新打开定位权限
     */
    locationSetting: function (e) {
        const that = this;
        if (!e.detail.authSetting["scope.userLocation"]) {
            that.setData({
                locationPermission: true
            });
        } else {
            that.setData({
                locationPermission: false
            });
            this.getCurrentLocationByServer();
        }
    },
    /**
     * 用户点击事件触发，微信原生地图选择页面
     * 根据微信定位，查询出详细地址，以及坐标
     */
    getCurrentLocation: function () {
        var that = this;
        wx.chooseLocation({
            success: function (res) {
                that.setData({
                    address: res.address,
                    latitude: res.latitude,
                    longitude: res.longitude
                })
            },
        })
    },
    /**
     * 设置事件描述 输入框中的值
     */
    getTextareaValue: function (e) {
        this.setData({
            textareaValue: e.detail.value
        });
    },
    /**
     *开始录音
     */
    handleTouchStart: function (e) {
        const than = this
        wx.getSetting({
            success(res) {
                if (!res.authSetting['scope.record']) {
                    //请求权限
                    than.setData({
                        recorderManager: wx.getRecorderManager()
                    })
                } else {
                    //拥有权限，直接获取
                    than.setData({
                        recorderManager: wx.getRecorderManager()
                    })
                    if (than.data.recorderManager != null) {
                        than.data.recorderManager.start()
                        //展示录音弹出层
                        than.setData({
                            isLuYin: true
                        })
                        than.luYinAnimation()
                    }
                }
            }
        })
    },
    /**
     *录音结束
     */
    handleTouchEnd: function (e) {
        const than = this
        clearInterval(this.luyinTimer)
        //关闭录音弹出层
        than.setData({
            isLuYin: false
        })
        than.data.recorderManager.stop()
        //录音结束回调
        than.data.recorderManager.onStop(res => {
            than.setData({
                lyFile: res
            })
        })
        clearInterval(this.luyinTimer)
    },
    /**
     * 重新录音
     */
    reLuYin: function (e) {
        this.setData({
            lyFile: null
        })
    },
    /**
     * 录音动画
     */
    luYinAnimation: function () {
        let i = 1
        this.luyinTimer = setInterval(() => {
            if (this.data.isLuYin) {
                i++
                i = i % 5
                this.setData({
                    isLuYinIndex: i + 1
                })
            }
        }, 250)
    },
    /**
     * 播放录音动画
     */
    yuYinAnimation: function () {
        let i = 1
        this.yuyinTimer = setInterval(() => {
            i++
            i = i % 3
            this.setData({
                isYuYinIndex: i + 1,
            })
            if (i === 0) {
                this.setData({
                    yuYinPath: '/common/image/yuyin.png'
                })
            } else {
                this.setData({
                    yuYinPath: '/common/image/yuyin_start_' + i + '.png'
                })
            }
        }, 400)
    },
    /**
     * 播放录音
     */
    onYuYinPlay: function (e) {
        const than = this
        if (than.data.isYuYinPlay) {
            //正在播放，准备停止的状态
            clearInterval(than.yuyinTimer)
            than.data.audio.stop()
            than.setData({
                yuYinPath: '/common/image/yuyin.png',
                isYuYinPlay: false
            })
        } else {
            //没播放，准备播放的状态
            than.setData({
                audio: wx.createInnerAudioContext(),
                isYuYinPlay: true
            })
            than.yuYinAnimation()
            than.data.audio.src = than.data.lyFile.tempFilePath
            than.data.audio.play()
            than.data.audio.onEnded(() => {
                clearInterval(than.yuyinTimer)
                than.setData({
                    yuYinPath: '/common/image/yuyin.png',
                    isYuYinPlay: false
                })
            })
        }
    },
    /**
     * 图片上传
     */
    afterRead: function (e) {
        const than = this
        for (let i = 0; i < e.detail.file.length; i++) {
            than.data.fileList.push({
                url: e.detail.file[i].path,
                name: e.detail.file[i].size
            })
        }
        than.setData({
            fileList: than.data.fileList
        })
    },

    /**
     * 删除图片
     */
    deleteImage: function (e) {
        const than = this
        const index = e.detail.index
        const deleteData = this.data.fileList.splice(index, 1)
        than.setData({
            fileList: than.data.fileList
        })

    },
    /**
     * 上报按钮
     * @param event
     */
    upEvent: function (event) {
        const than = this
        if (than.data.phone.length <= 0) {
            Toast.fail({
                message: '请输入联系电话！'
            })
            return;
        }
        if (than.data.radio == "00") {
            Toast.fail({
                message: '请选择事件类型！'
            })
            return;
        }
        const time = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0, 8)
        const areacode = app.globalData.areaCode
        const fileList1 = than.data.fileList
        let fileArray = []
        let isFile = false
        let fileNum = 0
        //上传附件
        //上传附件
        if (fileList1 != null) {
            for (let i = 0; i < fileList1.length; i++) {
                http.upFile(fileList1[i].url, "event")
                    .then((res) => {
                        fileArray.push({
                            attachment_name: res.data.name,
                            attachment_url: res.data.url,
                            attachment_type: 1
                        })
                        fileNum += 1
                    }, err => {
                        fileNum += 1
                    })
            }
        }
        if (than.data.lyFile != null) {
            http.upFile(than.data.lyFile.tempFilePath, "event")
                .then((res) => {
                    fileArray.push({
                        attachment_name: res.data.name,
                        attachment_url: res.data.url,
                        attachment_type: 2
                    })
                    isFile = true
                }, err => {
                    isFile = true
                })
        } else {
            isFile = true
        }
        if (than.data.textareaValue != null) {
            if (than.data.address != null) {
                Dialog.confirm({
                    title: "事件上报",
                    message: "确定要上报该事件吗？"
                }).then(() => {
                    //确认按钮
                    Toast.loading({
                        duration: 0,
                        forbidClick: true,
                        message: '正在上报，请稍等！'
                    })
                    var interval = setInterval(res => {
                        if (fileNum >= than.data.fileList.length && isFile) {
                            clearInterval(interval);
                            let { longitude, latitude } = app.gaoDeToBaidu(than.data.longitude, than.data.latitude)
                            http.postHeader("event/info/insert", {
                                'Authorization': app.globalData.accessToken
                            }, {
                                c_type_id: than.data.radio,
                                event_describe: than.data.textareaValue,
                                longitude: longitude,
                                latitude: latitude,
                                location: than.data.address,
                                occur_time: time,
                                area_code: areacode,
                                attachment_list: fileArray,
                                report_person_phone: than.data.phone,
                                source: 1
                            }).then((res) => {
                                if (res.data.code === 200) {
                                    //请求成功上传附件
                                    Toast.success({
                                        message: res.data.msg
                                    })
                                    setTimeout(() => {
                                        wx.navigateBack({
                                            delta: 2
                                        })
                                    }, 2000)
                                } else {
                                    Toast.fail({
                                        message: "提交失败，错误代码：" + res.data.msg + ",请联系管理员!"
                                    })
                                }
                            }, (err) => {
                                //请求失败
                                Toast.clear()
                                Toast.fail({
                                    message: "上报失败"
                                })
                            })
                        }
                    }, 1000)
                }).catch(() => {

                })
            } else {
                Toast.fail({
                    message: '暂未获取到事发地点，请重新选择地址！'
                })
            }
        } else {
            Toast.fail({
                message: '请输入事件描述信息！'
            })
        }
    },
    /**
     * 当前选中项的 name
     * @param event
     */
    onChange(event) {
        this.setData({
            radio: event.detail,
        });
    },
    onClick(event) {
        const { name } = event.currentTarget.dataset;
        const type_name = event.currentTarget.dataset.type_name;
        this.setData({
            radio: name,
            type: type_name
        });
    },
    /**
     * 随手报类别详情
     * @param event
     */
    getEventType: function (event) {
        const than = this
        let dataarr = [{
            type_name: "请选择事件类型",
            event_type_id: "00"
        }]
        http.get("unit_event_type/option")
            .then((res) => {
                if (res.data.code == 200) {
                    res.data.data.forEach((item, index) => {
                        dataarr.push({
                            type_name: item.type_name,
                            event_type_id: item.event_type_id
                        })
                    })
                    log.e(JSON.stringify(dataarr))
                    than.setData({
                        tpeylist: dataarr,
                    })
                    if (than.data.type == null)
                        than.setData({
                            radio: than.data.tpeylist[0].event_type_id,
                            type: than.data.tpeylist[0].type_name
                        })
                    than.getCurrentLocationByServer();
                }
            })
    },
    /**
     * 事件类别确定按钮
     * @param e
     */
    getEvent: function (e) {
        this.setData({
            show: false
        });

    },
    /**
     * 事件类型弹出层 关闭
     */
    onClose() {
        this.setData({
            show: false
        });
    },
    /**
     * 事件类型弹出层 显示
     */
    getType: function () {
        this.setData({
            show: true
        });
    },
    /**
     * 控制录音动画 false为不可见
     */
    recodeEnd: function () {
        this.setData({
            animationStatus: false
        })
    },
    /**
     * 控制录音动画 true为不可见
     */
    recodeClick: function () {
        this.setData({
            animationStatus: true
        })
    },
    /**
     * 获取电话号码
     */
    getPhoneNum: function () {
        const than = this
        http.get("people_info/people", {
            people_id: app.globalData.userInfo.people_id,//'8a8080d373991a3b0173991a3bce0000'
        }).then((res) => {
            if (res.data.code != 200) {
                wx.getStorage({
                    key: "phone",
                    success: function (res) {
                        if (res.data.length == 11) {
                            than.setData({
                                phone: res.data
                            })
                        } else {
                            Dialog.confirm({
                                title: '提示',
                                message: '为了方便您的操作，请先绑定手机号',
                                confirmButtonOpenType: "getPhoneNumber"
                            }).then(() => {
                                setTimeout(() => {
                                    Dialog.close();
                                }, 1000);
                            }).catch(() => {
                                Dialog.close();
                            });
                        }
                    },
                    fail: function (res) {
                        Dialog.confirm({
                            title: '提示',
                            message: '为了方便您的操作，请先绑定手机号',
                            confirmButtonOpenType: "getPhoneNumber"
                        }).then(() => {
                            setTimeout(() => {
                                Dialog.close();
                            }, 1000);
                        }).catch(() => {
                            Dialog.close();
                        });
                    }
                })
            } else {
                if (res.data.data.phone.length <= 0) {
                    wx.getStorage({
                        key: "phone",
                        complete: function (res) {
                            log.e(JSON.stringify(res))
                            if (res.errMsg != 'getStorage:fail data not found') {
                                than.setData({
                                    phone: res.data
                                })
                            } else {
                                Dialog.confirm({
                                    title: '提示',
                                    message: '为了方便您的操作，请先绑定手机号',
                                    confirmButtonOpenType: "getPhoneNumber"
                                }).then(() => {
                                    setTimeout(() => {
                                        Dialog.close();
                                    }, 1000);
                                }).catch(() => {
                                    Dialog.close();
                                });
                            }
                        }
                    })
                } else {
                    than.setData({
                        phone: res.data.data.phone
                    })
                }
            }
        })
    },
    /**
     * 电话号码 输入框中的值
     */
    getTextValue: function (e) {
        const than = this
        than.setData({
            phone: e.detail.value
        })
    },
    getPhoneNumber: function (e) {
        const than = this
        wx.login({
            success: function (r) {
                log.e(JSON.stringify(e) + JSON.stringify(r))
                http.get("applet/user/wxDecryptPhone", {
                    appid: app.globalData.appId,
                    code: r.code,
                    iv: e.detail.iv,
                    encryptedData: e.detail.encryptedData,
                }
                ).then((res) => {
                    if (res.data.code == 200) {
                        wx.setStorage({
                            key: "phone",  // 存储的key值
                            data: res.data.data.phoneNumber   // 需要存储的值
                        })
                        than.setData({
                            phone: res.data.data.phoneNumber
                        })
                    }
                })
            }
        })
    },
})